package com.cinema.util;

import javax.servlet.http.HttpServletRequest;

/**
 * Image path utility class
 */
public class ImagePathUtil {

    /**
     * Convert full URL to relative path for database storage
     * @param fullUrl Full URL like: /cinema_booking_system/images/movies/abc123.jpg
     * @return Relative path like: /images/movies/abc123.jpg
     */
    public static String toRelativePath(String fullUrl) {
        if (fullUrl == null || fullUrl.trim().isEmpty()) {
            return null;
        }

        // If already relative path, return directly
        if (fullUrl.startsWith("/images/")) {
            return fullUrl;
        }

        // If contains contextPath, extract relative path part
        int imagesIndex = fullUrl.indexOf("/images/");
        if (imagesIndex >= 0) {
            return fullUrl.substring(imagesIndex);
        }

        // If HTTP full URL, extract path part
        if (fullUrl.startsWith("http")) {
            try {
                java.net.URL url = new java.net.URL(fullUrl);
                String path = url.getPath();
                int imagesIdx = path.indexOf("/images/");
                if (imagesIdx >= 0) {
                    return path.substring(imagesIdx);
                }
            } catch (Exception e) {
                System.err.println("Failed to parse URL: " + fullUrl);
            }
        }

        return fullUrl;
    }

    /**
     * Convert relative path to full URL for frontend display
     * @param relativePath Relative path like: /images/movies/abc123.jpg
     * @param request HTTP request object
     * @return Full URL like: /cinema_booking_system/images/movies/abc123.jpg
     */
    public static String toFullUrl(String relativePath, HttpServletRequest request) {
        if (relativePath == null || relativePath.trim().isEmpty()) {
            return null;
        }

        // If already full URL, return directly
        if (relativePath.startsWith("http") || relativePath.contains(request.getContextPath())) {
            return relativePath;
        }

        // If relative path, add contextPath
        if (relativePath.startsWith("/images/")) {
            return request.getContextPath() + relativePath;
        }

        // If path doesn't start with /, add /
        if (!relativePath.startsWith("/")) {
            relativePath = "/" + relativePath;
        }

        return request.getContextPath() + relativePath;
    }

    /**
     * Convert relative path to full URL for frontend display
     * @param relativePath Relative path like: /images/movies/abc123.jpg
     * @param contextPath Context path like: /cinema_booking_system
     * @return Full URL like: /cinema_booking_system/images/movies/abc123.jpg
     */
    public static String toFullUrl(String relativePath, String contextPath) {
        if (relativePath == null || relativePath.trim().isEmpty()) {
            return null;
        }

        // If already full URL, return directly
        if (relativePath.startsWith("http") || relativePath.contains(contextPath)) {
            return relativePath;
        }

        // If relative path, add contextPath
        if (relativePath.startsWith("/images/")) {
            return contextPath + relativePath;
        }

        // If path doesn't start with /, add /
        if (!relativePath.startsWith("/")) {
            relativePath = "/" + relativePath;
        }

        return contextPath + relativePath;
    }

    /**
     * Generate relative path from filename
     * @param fileName File name like: abc123.jpg
     * @param subDirectory Sub directory like: movies, avatars
     * @return Relative path like: /images/movies/abc123.jpg
     */
    public static String generateRelativePath(String fileName, String subDirectory) {
        if (fileName == null || fileName.trim().isEmpty()) {
            return null;
        }

        if (subDirectory == null || subDirectory.trim().isEmpty()) {
            subDirectory = "default";
        }

        // Clean sub directory path
        subDirectory = subDirectory.trim().replaceAll("/+", "/");
        if (subDirectory.startsWith("/")) {
            subDirectory = subDirectory.substring(1);
        }
        if (subDirectory.endsWith("/")) {
            subDirectory = subDirectory.substring(0, subDirectory.length() - 1);
        }

        return "/images/" + subDirectory + "/" + fileName.trim();
    }

    /**
     * Validate if image path format is correct
     * @param imagePath Image path
     * @return true if format is correct
     */
    public static boolean isValidImagePath(String imagePath) {
        if (imagePath == null || imagePath.trim().isEmpty()) {
            return false;
        }

        // Check if supported image format
        String lowerPath = imagePath.toLowerCase();
        return lowerPath.endsWith(".jpg") ||
               lowerPath.endsWith(".jpeg") ||
               lowerPath.endsWith(".png") ||
               lowerPath.endsWith(".gif") ||
               lowerPath.endsWith(".webp");
    }

    /**
     * Get default image path
     * @param imageType Image type: poster, avatar etc
     * @return Default image relative path
     */
    public static String getDefaultImagePath(String imageType) {
        switch (imageType.toLowerCase()) {
            case "poster":
            case "movie":
                return "/images/default-poster.jpg";
            case "avatar":
            case "user":
                return "/images/default-avatar.jpg";
            default:
                return "/images/default.jpg";
        }
    }

    /**
     * Clean image path, remove extra slashes and spaces
     * @param imagePath Original image path
     * @return Cleaned path
     */
    public static String cleanImagePath(String imagePath) {
        if (imagePath == null) {
            return null;
        }

        // Remove leading and trailing spaces
        imagePath = imagePath.trim();

        if (imagePath.isEmpty()) {
            return null;
        }

        // Replace multiple consecutive slashes with single slash
        imagePath = imagePath.replaceAll("/+", "/");

        // Ensure starts with / (if relative path)
        if (!imagePath.startsWith("http") && !imagePath.startsWith("/")) {
            imagePath = "/" + imagePath;
        }

        return imagePath;
    }

    /**
     * Check if path needs fixing
     * @param imagePath Image path
     * @return true if needs fixing
     */
    public static boolean needsFix(String imagePath) {
        if (imagePath == null || imagePath.trim().isEmpty()) {
            return false;
        }

        // If contains ${pageContext.request.contextPath}, needs fixing
        if (imagePath.contains("${pageContext.request.contextPath}")) {
            return true;
        }

        // If HTTP full URL but should be relative path, needs fixing
        if (imagePath.startsWith("http") && imagePath.contains("/images/")) {
            return true;
        }

        // If not starting with /images/ relative path, might need fixing
        if (!imagePath.startsWith("/images/") && !imagePath.startsWith("http")) {
            return true;
        }

        return false;
    }
}
